package com.atguigu.gmall.list.receiver;

import com.atguigu.gmall.constant.MqConst;
import com.atguigu.gmall.list.service.SearchService;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ListReceiver {

    @Autowired
    private SearchService searchService;

    @Autowired
    private ProductFeignClient productFeignClient;

    //  监听消息
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_UPPER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            key = {MqConst.ROUTING_GOODS_UPPER}
    ))
    public void goodsUpper(Long skuId, Message message, Channel channel){
        try {
            //  判断
            if (skuId!=null){
                //  从缓存来的---> 可能会出现数据不一致！
                SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
                if (skuInfo.getIsSale().intValue()==1){
                    searchService.upperGoods(skuId);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  监听消息
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_LOWER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            key = {MqConst.ROUTING_GOODS_LOWER}
    ))
    public void goodsLower(Long skuId, Message message, Channel channel){
        try {
            //  判断
            if (skuId!=null){
                SkuInfo skuInfo = this.productFeignClient.getSkuInfo(skuId);
                //  当前字段属于上架的时候，才会走下架！
                if (skuInfo.getIsSale().intValue()==0){
                    searchService.lowerGoods(skuId);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
